package com.bw.car_module.carlist;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.room.Room;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.bw.base_application_sdk.BaseApplication;
import com.bw.car_module.R;
import com.bw.car_module.carlist.dao.CartDataBase;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.common.providerservice.CheckLoginApi;
import com.bw.common.utils.ToastShowUtils;
import com.bw.network_sdk.BaseEntity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class CartViewModel extends BaseViewModel<CartRespository>
        implements OnItemClickListener, OnItemChildClickListener {

    public ObservableField<String>edtStr = new ObservableField<>("编辑");
    public ObservableField<String>payTxt = new ObservableField<>("支付");
    public ObservableField<Boolean>allCheck = new ObservableField<>(false);
    public ObservableField<String>allPrice = new ObservableField<>("0");
    public ObservableField<List<CartValueEntity>>cartList = new ObservableField<>();
    private CheckLoginApi checkLoginApi;
    private  CartDataBase dataBase;
    private boolean edtFlag = false;//编辑状态下底部radiobutton选中状态
    private boolean payFlag = false;//选择去支付状态下底部radiobutton选中状态
    private OffLineCartEntity offLineCartEntity;
    private CartEntity cartEntity;
    private List<CartValueEntity>equalsList = new ArrayList<>();//在线以及离线购物车相同数据
    private List<CartValueEntity>unEqualsList = new ArrayList<>();//在线以及离线购物车不同数据
//    private int num = 0;

    public void checkAllListener(){
        //区分当前状态是在全选编辑数据或待购物数据
        List<CartValueEntity>list = new ArrayList<>();
        list.addAll(cartList.get());
        if(edtStr.get().equals("编辑")){
            //购物车选中数据改变
            //确认全选或全不选状态
            boolean flag = true;//true处于全选状态,false非全选状态
            for (int i = 0;i < list.size();i ++){
                if (!list.get(i).selFlag)
                    flag = false;
            }
            //更新全选状态
            for (int i = 0;i < list.size();i ++){
                list.get(i).selFlag = !flag;
            }
            //计算总价
            totalPrice();
        }else {
            //购物车删除数据改变
            boolean flag = true;//true处于全选状态,false非全选状态
            for (int i = 0;i < list.size();i ++){
                if (!list.get(i).edtSelFlag)
                    flag = false;
            }
            for (int i = 0;i < list.size();i ++){
                list.get(i).edtSelFlag = !flag;
            }
        }
        cartList.set(list);
    }

    public void subCar(){
        //用户登录校验
        if (checkLoginApi.checkLogin()){
            //选择支付得购物车数据生成订单接口
            //获取要支付得商品集合
            if (cartList.get()==null)
                return;
            if (cartList.get().size() == 0)
                return;
            List<CartValueEntity>list = new ArrayList<>();
            float allPrice = 0f;
            for (CartValueEntity entity:cartList.get()){
                if (entity.selFlag){
                    list.add(entity);
                    float price = Float.valueOf(
                            TextUtils.isEmpty(entity.goods_price)?"0"
                                    :entity.goods_price)*
                            Integer.valueOf(entity.goods_count);
                    allPrice +=price;
                }
            }
            Map<String,Object>map = new HashMap<>();
            map.put("userId",checkLoginApi.getUserId());
            map.put("totalPrice",allPrice);
            map.put("goodsList",list);
            respository.requestSubmitCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else {
            //跳转登录界面
            ARouter.getInstance().build("/user/loginactivity")
                    .navigation();
        }
    }

    public void edtClickListener(){
        List<CartValueEntity>list = new ArrayList<>();
        list.addAll(cartList.get());
        if(edtStr.get().equals("编辑")){
            edtStr.set("完成");
            allPrice.set("选择");
            payFlag = allCheck.get();
            allCheck.set(edtFlag);
            for (int i = 0;i < list.size();i ++){
                list.get(i).edtFlag = true;
            }
        }else {
            edtStr.set("编辑");
            edtFlag = allCheck.get();
            allCheck.set(payFlag);
            //完成编辑->删除选中得数据->
            List<CartValueEntity> cartValueEntityList = new ArrayList<>();
            //配置本地room数据库删除得数据
            List<Long>ids = new ArrayList<>();//保存删除接口中得id
            for (int i = 0;i < list.size();i ++){
                list.get(i).edtFlag = false;
                if (list.get(i).edtSelFlag) {
                    cartValueEntityList.add(list.get(i));
                    ids.add(list.get(i).id);
                }
            }
            if (checkLoginApi.checkLogin()){
                Map<String,Object>map=new HashMap<>();
                map.put("cartIdList",ids);
                respository.requestDelCart(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this);
            }else {
                respository.delCart(cartValueEntityList,dataBase.dao())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this);
            }

            totalPrice();
        }
        cartList.set(list);
    }

    //减少商品数量
    private void minuteCount(int position){
        CartValueEntity entity = cartList.get().get(position);
        entity.goods_count-=1;
        if (checkLoginApi.checkLogin()){
            //已登录
            Map<String,Object>map=new HashMap<>();
            List<Long>ids = new ArrayList<>();
            ids.add(entity.id);
            map.put("cartIdList",ids);
            List<CartValueEntity>list = new ArrayList<>();
            list.add(entity);
            map.put("addCartList",list);
            respository.requestUpdateCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else {
            //未登录
//            cartList.get().get(position).goods_count-=1;
            respository.updateCart(cartList.get(),
                    dataBase.dao()).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }
    }
    //增加商品数量
    private void pulseCount(int position){
        CartValueEntity entity = cartList.get().get(position);
        entity.goods_count +=1;
        if (checkLoginApi.checkLogin()){
            //已登录
            Map<String,Object>map=new HashMap<>();
            List<Long>ids = new ArrayList<>();
            ids.add(entity.id);
            map.put("cartIdList",ids);
            List<CartValueEntity>list = new ArrayList<>();
            list.add(entity);
            map.put("addCartList",list);
            respository.requestUpdateCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else {
            //未登录
//            cartList.get().get(position).goods_count+=1;
            respository.updateCart(cartList.get(), dataBase.dao()).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }
    }
    //计算全部待支付金额
    private void totalPrice(){
        if (cartList.get() == null)
            return;
        if (cartList.get().size() == 0)
            return;
        float price = 0f;
        boolean allFlag = true;
        for (CartValueEntity valueEntity:cartList.get()){
            if (TextUtils.isEmpty(valueEntity.goods_price))
                continue;
            if (valueEntity.selFlag) {
                float p = Float.valueOf(valueEntity.goods_price);
                price += p;
            }else
                allFlag = false;
        }
        //编辑状态下计算总金额
        if(edtStr.get().equals("编辑"))
            allPrice.set(""+price);
        else
            allPrice.set("选择");
        allCheck.set(allFlag);
    }

    @Override
    public void onResult(BaseEntity entity) {
        if(entity instanceof CartEntity){
            //在线数据
            cartEntity = (CartEntity) entity;
            cartList.set(cartEntity.data);
            totalPrice();
        }else if (entity instanceof OffLineCartEntity){
            //离线数据
            offLineCartEntity = (OffLineCartEntity) entity;
            //用户未登录更新数据
            if (!checkLoginApi.checkLogin()){
                cartList.set(offLineCartEntity.data);
                totalPrice();
            }else {
                //用户登录->同步数据离线购物车
                syncCart();
            }
        }else if (entity instanceof AddCartEntity ||
                entity instanceof DelCartEntity){
//            if (entity.message.equals("添加购物车成功"))
//                num +=1;
            //更新数据为:先删除在添加->成功后->数据列表刷新
            Map<String,Object>map = new HashMap<>();
            map.put("id",checkLoginApi.getUserId());
            respository.requestCartList(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else if (entity instanceof OffLineUpdateEntity ||
                entity instanceof OffLineDelEntity){
            respository.selCart(dataBase.dao())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else if (entity instanceof SubmitCartEntity){
            SubmitCartEntity submitCartEntity = (SubmitCartEntity) entity;
            Bundle bundle = new Bundle();
            bundle.putLong("orderId", submitCartEntity.data);
            startBundPage("/order/confirmactivity",bundle);
        }
    }

    @Override
    public void onComplete() {
        super.onComplete();
//        if (num>0){
//            //执行完合并操作
//            //保证合并数据成功性
//            //更新得数据与不同得数据集合数量相同
//            //将不同得数据全部提交到在线购物车列表
//            if (num == unEqualsList.size()){
//                //清处本地离线购物车数据
//                respository.delCart(dataBase.dao())
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(this);
//                //获取最新在线购物车数据->同步离线购物车完成后刷新在线数据
//                Map<String,Object>map = new HashMap<>();
//                map.put("id",checkLoginApi.getUserId());
//                respository.requestCartList(map)
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(this);
//            }
//        }
//        if (offLineCartEntity!=null&&cartEntity!=null){
//            if (offLineCartEntity.data == null)
//                return;
//            if (offLineCartEntity.data.size() == 0)
//                return;
//            //具有离线数据以及在线数据
//            syncCart();
//        }
    }

    @Override
    protected void initData() {
        checkLoginApi = (CheckLoginApi) ARouter.getInstance()
                .build("/user/checklogin").navigation();
        if (checkLoginApi.checkLogin()){
            //已登陆
            Map<String,Object>map = new HashMap<>();
            map.put("id",checkLoginApi.getUserId());
            respository.requestCartList(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
            dataBase = Room.databaseBuilder(BaseApplication.getInstance(),
                    CartDataBase.class,"cart.db").build();
            respository.selCart(dataBase.dao())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }else {
            dataBase = Room.databaseBuilder(BaseApplication.getInstance(),
                    CartDataBase.class,"cart.db").build();
            respository.selCart(dataBase.dao())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.car_item_radio){
            //改变待生成订单状态下得选择值->selflag
            List<CartValueEntity>list = new ArrayList<>();
            list.addAll(cartList.get());
            list.get(position).selFlag = !list.get(position).selFlag;
            cartList.set(list);
            //计算总价
            totalPrice();
        }else if (id == R.id.car_item_left){
            minuteCount(position);
        }else if (id == R.id.car_item_right){
            pulseCount(position);
        }else if (id == R.id.car_item_edt_radio){
            //改变编辑状态下得选择值->edtselflag
            List<CartValueEntity>list = new ArrayList<>();
            list.addAll(cartList.get());
            list.get(position).edtSelFlag = !list.get(position).edtSelFlag;
            cartList.set(list);
            totalPrice();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

    }

    //同步购物车数据
    public void syncCart(){
        LogUtils.e("syncCart()");
//        num = 0;
        //校验用户是否登录->未登录->跳出当前方法
//        if (!checkLoginApi.checkLogin()){
//            LogUtils.e("用户未登录");
//            return;
//        }
        //获取离线购物车数据->判断数量
        if (offLineCartEntity == null){
            LogUtils.e("无离线购物车数据");
            return;
        }
        if (offLineCartEntity.data == null){
            LogUtils.e("无离线购物车数据");
            return;
        }
        if (offLineCartEntity.data.size() == 0){
            LogUtils.e("无离线购物车数据");
            return;
        }
        //当前状态为用户已登录且用户具有离线购物车数据
        //cartentity与offlinecarentity比较
        //无在线购物车情况->同步离线购物车数据
        for (int i = 0;i < offLineCartEntity.data.size();i ++){
            offLineCartEntity.data.get(i).user_id = checkLoginApi.getUserId();
        }
        if (cartEntity == null){
            unEqualsList.addAll(offLineCartEntity.data);
            Map<String,Object>map=new HashMap<>();
            map.put("addCartList",unEqualsList);//离线购物车与在线购物车不同得列表数据
            respository.requestUpdateCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
            return;
        }
        if (cartEntity.data == null){
            unEqualsList.addAll(offLineCartEntity.data);
            Map<String,Object>map=new HashMap<>();
            map.put("addCartList",unEqualsList);//离线购物车与在线购物车不同得列表数据
            respository.requestUpdateCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
            return;
        }
        if (cartEntity.data.size() == 0){
            unEqualsList.addAll(offLineCartEntity.data);
            Map<String,Object>map=new HashMap<>();
            map.put("addCartList",unEqualsList);//离线购物车与在线购物车不同得列表数据
            respository.requestUpdateCart(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);
            return;
        }
        //在线购物车具有数据,离线购物车也具有数据
        //不同数据->添加到在线购物车
        //相同数据->合并数量->清除掉相同得对应购物车数据
        //由于接口中不具有修改购物车数据接口,先删除购物车数据
        //相同数据合并到不同数据中去->完整得不同购物车数据列表
        //提交购物车数据->提交成功->清空离线购物车表中数据
        //获取最新在线购物车列表数据
        //1.双层嵌套循环遍历数据
        for (int i = 0;i < offLineCartEntity.data.size();i ++){
            CartValueEntity offlineEntity = offLineCartEntity.data.get(i);
            boolean flag = true;
            for (int j = 0;j < cartEntity.data.size(); j ++){
                CartValueEntity onlineEntity = cartEntity.data.get(j);
                if (EqualeUtils.equaleValueEntity(onlineEntity,offlineEntity)){
                    onlineEntity.goods_count = onlineEntity.goods_count
                            +offlineEntity.goods_count;
                    equalsList.add(onlineEntity);
                    flag = false;
                }
            }
            if (flag){
                //当前离线数据无相同得在线数据->离线数据与在线数据不同
                unEqualsList.add(offlineEntity);
            }
        }
        //记录要删除数据得id->相同数据得id
        List<Long>ids = new ArrayList<>();
        for (CartValueEntity entity : equalsList){
            ids.add(entity.id);
        }
        unEqualsList.addAll(equalsList);
        //修改在线购物车数据列表接口
        Map<String,Object>map=new HashMap<>();
        map.put("cartIdList",ids);//要删除得相同得在线购物车列表数据
        map.put("addCartList",unEqualsList);//离线购物车与在线购物车不同得列表数据
        respository.requestUpdateCart(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

}
